// Copyright (C) 2009 Mihai Preda

package calculator;

import android.content.Context;
import java.io.*;
import java.util.ArrayList;
import org.javia.arity.*;

public class Defs extends FileHandler
{
    private static final int SIZE_LIMIT = 50;
    private ArrayList<String> lines = new ArrayList<String>();
    private Symbols symbols;

    Defs(Context context, Symbols symbols)
    {
    	super(context, "defs", 1);
    	
    	this.symbols = symbols;
        symbols.pushFrame();
        load();
    }

    public void clear()
    {
        getLines().clear();
        
        symbols.popFrame();
        symbols.pushFrame();
    }

    public int size()
    {
        return getLines().size();
    }

    void doRead(DataInputStream is) throws IOException
    {
    	int size = is.readInt();
    	
    	for (int i = 0; i < size; ++i)
    	{
    		String line = is.readUTF();
    		getLines().add(line);
    		
    		try
    		{
    			symbols.define(symbols.compileWithName(line));
    		}
    		catch (SyntaxException e)
    		{
    			// ignore
    		}
    	}
    }

    void doWrite(DataOutputStream os) throws IOException
    {
    	os.writeInt(getLines().size());
    	
    	for (String s : getLines())
    		os.writeUTF(s);		
    }

    void add(String text)
    {
    	if (getLines().size() >= SIZE_LIMIT)
    		getLines().remove(0);

    	getLines().add(text);
    }

	public ArrayList<String> getLines()
	{
		return lines;
	}
}
